package com.xiaodou.mjf.web.xface.user.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.service.FeedbackService;
import com.xiaodou.mjf.entity.core.Feedback;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.ResultCode;

@RestController
@RequestMapping("v1/feedback")
public class FeedbackController extends ApiController{
	
	@Resource
	FeedbackService feedbackService;
	
    @RequestMapping(value = "",method = RequestMethod.POST)
	public Map<String, Object> feedback(
			@RequestHeader(required = false) String uid, String comments) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		if (StringUtils.isBlank(comments)) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		List<Feedback> feedbacks = feedbackService.getInfoBymemberId(uid);
		if (feedbacks.size() > 0) {
			if (DateUtils.compare(DateUtils.getCurrentTime(),
					DateUtils.addMinutes(feedbacks.get(0).getCreateTime(), 5)) < 0) {
				return failure(ResultCode.RETRY_AGAIN);
			}
		}


		Feedback feedback = new Feedback();
		feedback.setMemberId(uid);
		try {
			feedback.setContent(URLDecoder.decode(comments, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		feedback.setProcessStatus(Feedback.PROCESS_STATUS_TODO);
		feedback.setStatus(Feedback.NORMAL);
		try {
			feedbackService.save(feedback);
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.UNRECOGNIZED_ERROR);
		}

		Map<String, Object> result = success();

		return result;
	}
}
